package com.cq.hd.app.biz;

import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.entity.hf.HfUploadVo;
import com.cq.hd.common.enums.biz.HfFileTypeEnum;
import com.cq.hd.common.enums.biz.UploadFileUseEnum;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.FileUtils;
import com.cq.hd.system.api.HfApi;
import com.cq.hd.system.api.OssApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class UploadBiz {

    @Autowired
    private OssApi ossApi;

    @Autowired
    private HfApi hfApi;

    public String upload(MultipartFile file, Integer type, HttpServletRequest request) {
        if (file == null || file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
            Throw.isBusinessException("文件不存在");
        }

        if (file.getSize() > Constant.MAX_VIDEO_FILE_SIZE) {
            Throw.isBusinessException("文件大小不能超过10M");
        }

        String uploadPath = UploadFileUseEnum.matchNameByCode(type);
        if (StringUtils.isEmpty(uploadPath)) {
            Throw.isBusinessException("上传图片用途值错误");
        }

        return ossApi.uploadFile(file, uploadPath, "").unpack();
    }

    public HfUploadVo hfUpload(MultipartFile file, String type, HttpServletRequest request) {
        if (file == null || file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename())) {
            Throw.isBusinessException("图片不存在");
        }

        if (StringUtils.isEmpty(type) || HfFileTypeEnum.typeOfValue(type) == null) {
            Throw.isBusinessException("图片类型不匹配");
        }

        if (FileUtils.isContain(Constant.IMG_FILE_EXTENSIONS, file.getOriginalFilename())) {
            Throw.isBusinessException("请上传图片");
        }

        if (file.getSize() > Constant.MAX_FILE_SIZE) {
            Throw.isBusinessException("图片最大支持5M");
        }

        String name = UploadFileUseEnum.HF.getName();
        String ossImgPath = ossApi.uploadFile(file, name, "").unpack();
        if (StringUtils.isEmpty(ossImgPath)) {
            Throw.isBusinessException("上传失败");
        }

        String fileId = hfApi.imgUpload(file, type).unpack();
        if (StringUtils.isEmpty(fileId)) {
            Throw.isBusinessException("上传失败");
        }

        HfUploadVo hfUploadVo = new HfUploadVo();
        hfUploadVo.setImgUrl(ossImgPath);
        hfUploadVo.setFileId(fileId);

        return hfUploadVo;
    }

}
